package jianzhi;

import niuke.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * description:
 * author:zt
 * date:2021-10-21
 */
//从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
public class jianzhi32_2 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<TreeNode> list = new LinkedList<>();
        list.addLast(root);
        while (!list.isEmpty()){
            ArrayList<Integer> path = new ArrayList<>();
            for (int i = list.size(); i > 0; i--) {
                TreeNode node = list.removeFirst();
                if (node.left!=null) list.addLast(node.left);
                if (node.right!=null) list.addLast(node.right);
                path.add(node.val);
            }
            res.add(path);
        }
        return res;
    }
}
